package com.ruoyi.service;

import com.ruoyi.common.core.domain.model.LoginUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserRoleService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 根据 Token 获取用户角色信息
     */
    public LoginUser getLoginUserByToken(String token) {
        // Redis 键格式（若依默认）
        String redisKey = "login_tokens:" + token;
        // 从 Redis 中获取 LoginUser 对象
        return (LoginUser) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 获取用户角色名称列表
     */
    public List<String> getRoleNamesByToken(String token) {
        LoginUser loginUser = getLoginUserByToken(token);
        if (loginUser != null && loginUser.getUser() != null) {
            return loginUser.getUser().getRoles().stream()
                    .map(role -> role.getRoleName())
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 获取用户角色编码列表
     */
    public List<String> getRoleKeysByToken(String token) {
        LoginUser loginUser = getLoginUserByToken(token);
        if (loginUser != null && loginUser.getUser() != null) {
            return loginUser.getUser().getRoles().stream()
                    .map(role -> role.getRoleKey())
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}